package com.jfinal.common.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.erp.common.model.SystemUser;

import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.ext.shrio.ShiroPrincipal;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

public abstract class BaseController extends Controller {

	private final Logger logger = LoggerFactory.getLogger(BaseController.class);

	public String getBasePath() {
		ServletContext servletContext = JFinal.me().getServletContext();
		return servletContext.getContextPath();
	}

	public String getRealPath() {
		ServletContext servletContext = JFinal.me().getServletContext();
		return servletContext.getRealPath("");
	}

	public String getIp() {
		String ipdtr = getRequest().getRemoteAddr();
		return ipdtr;
	}

	public void setCurrentUser(SystemUser newuser) {
		getSession().setAttribute("currentUser", newuser);
	}

	public SystemUser getCurrentUser() {
		return (SystemUser) getSession().getAttribute("currentUser");
	}

	public SystemUser getCurrentUserFromDb() {
		ShiroPrincipal user = (ShiroPrincipal) SecurityUtils.getSubject()
				.getPrincipal();
		return user.getUser();
	}

	public Page<?> page(Model<?> model, int pageNumber, int pageSize) {
		Table table = TableMapping.me().getTable(model.getClass());
		System.out.println(TableMapping.me().getTable(model.getClass()));

		String sql = "select * ";
		String from = " from " + table.getName() + " where  1 = 1 ";

		List<Object> args = new ArrayList<Object>();
		Map<String, Class<?>> columnmap = table.getColumnTypeMap();

		for (Map.Entry<String, Class<?>> entry : columnmap.entrySet()) {
			String cname = entry.getKey();
			Class<?> type = entry.getValue();
			Object val = model.get(cname);
			if (val != null) {

				if (type == String.class) {// 字符串
					from += " and  " + cname + " like  ? ";
					args.add("%" + val + "%");
				} else {
					from += " and  " + cname + " =  ? ";
					args.add(val);
				}

			}
		}

		return model.paginate(pageNumber, pageSize, sql, from, args.toArray());
	}
}
